# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "泰无忧·住院保（2019版）"

    # 生产产品数据
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 17)],
                # 保障天数
                "days": ["1y"],
                # 意外伤残/死亡
                "accident_death": ["100000", "200000"],
                # 为谁投保
                "forWho": ["儿女"],
                # 职业
                "professions": [""]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(18, 51)],
                # 保障天数
                "days": ["1y"],
                # 意外伤残/死亡
                "accident_death": ["100000", "200000", "300000"],
                # 为谁投保
                "forWho": ["本人/父母/配偶"],
                # 职业
                "professions": [item for item in self.getProfessionInfo().values()]

            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(51, 56)],
                # 保障天数
                "days": ["1y"],
                # 意外伤残/死亡
                "accident_death": ["20000"],
                # 为谁投保
                "forWho": ["本人/父母/配偶"],
                # 职业
                "professions": [item for item in self.getProfessionInfo().values()]

            }
        }
        data = {}
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["days"], plan[k]["accident_death"], plan[k]["forWho"],
                             plan[k]["professions"]):
                if v[2] == "100000":
                    accident_medical = "10000"
                    disease_hospital = "10000"
                elif v[2] == "200000":
                    accident_medical = "20000"
                    disease_hospital = "20000"
                elif v[2] == "200000":
                    accident_medical = "30000"
                    disease_hospital = "30000"
                else:
                    accident_medical = "10000"
                    disease_hospital = "10000"
                data["year"] = v[0]
                data["days"] = v[1]
                data["accident_death"] = v[2]
                data["forWho"] = v[3]
                data["professions"] = '""' if v[4] == "" else "'" + json.dumps(v[4], ensure_ascii=False) + "'"
                data["accident_medical"] = accident_medical
                data["disease_hospital"] = disease_hospital
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):
        if dt["forWho"] == "儿女":
            data = {
                "calculateData": {"calstartDate": "2020-04-21 00:00:00", "calinsuredAge": dt["year"], "insuredInfo": [
                    {"calinsuredRelationship": "40", "minimum": "0", "maximum": "17", "planAgeMax": "49",
                     "planAgeMin": "0",
                     "planCode": "10", "profession": "3"}], "calinsuredPeriod": "Y1", "planLiabilityList": [
                    {"liabilityId": "1122031", "amount": dt["accident_death"], "liabilityName": "人身意外伤害身故/伤残保险",
                     "liabilityAmount": str(int(int(dt["accident_death"]) / 10000)) + "万"},
                    {"liabilityId": "1122032", "amount": dt["accident_medical"], "liabilityName": "附加意外伤害医疗保险",
                     "liabilityAmount": str(int(int(dt["accident_medical"]) / 10000)) + "万"},
                    {"liabilityId": "100019", "amount": dt["disease_hospital"], "liabilityName": "疾病住院医疗保险",
                     "liabilityAmount": str(int(int(dt["disease_hospital"]) / 10000)) + "万"}],
                                  "liabilityContents": [{"liabilityId": "1122031", "amount": dt["accident_death"],
                                                         "liabilityName": "人身意外伤害身故/伤残保险",
                                                         "liabilityAmount": str(
                                                             int(int(dt["accident_death"]) / 10000)) + "万"},
                                                        {"liabilityId": "1122032", "amount": dt["accident_medical"],
                                                         "liabilityName": "附加意外伤害医疗保险", "liabilityAmount": str(
                                                            int(int(dt["accident_medical"]) / 10000)) + "万"},
                                                        {"liabilityId": "100019", "amount": dt["disease_hospital"],
                                                         "liabilityName": "疾病住院医疗保险", "liabilityAmount": str(
                                                            int(int(dt["disease_hospital"]) / 10000)) + "万"}],
                                  "planId": "1307A02V01"},
                "exchangeData": {"memberId": "", "memberToken": "", "applicationId": "1250987393384046592",
                                 "applicationToken": "528ca32e9707feffe3a1b26e7046d2a9",
                                 "workqueueId": "1121711509709635584", "channelId": "3", "platformId": "pc",
                                 "referId": ""}, "insuredData": [
                    {"insuredProfessionLevel": "1", "insuredProfessionText": "学龄前儿童", "insuredProfession": "02001001"}]}
        else:
            # 判断职业
            if "水产养殖质量管理员" in dt["professions"]:
                level = "1"
                text = "水产养殖质量管理员"
            elif "菌类园艺工" in dt["professions"]:
                level = "2"
                text = "菌类园艺工"
            elif "动物疫病防治员" in dt["professions"]:
                level = "3"
                text = "动物疫病防治员"
            else:
                level = "4"
                text = "农夫或农业工人"

            if dt["accident_death"] == "20000":
                planId = "1307A02V03"
            else:
                planId = "1307A02V02"
            data = {
                "calculateData": {"calstartDate": "2020-04-21 00:00:00", "calinsuredAge": dt["year"], "insuredInfo": [
                    {"calinsuredRelationship": "01", "minimum": "18", "maximum": "65", "planAgeMax": "49",
                     "planAgeMin": "0",
                     "planCode": "10", "profession": level}], "calinsuredPeriod": "Y1", "planLiabilityList": [
                    {"liabilityId": "1122031", "amount": dt["accident_death"], "liabilityName": "人身意外伤害身故/伤残保险",
                     "liabilityAmount": str(int(int(dt["accident_death"]) / 10000)) + "万"},
                    {"liabilityId": "1122032", "amount": dt["accident_medical"], "liabilityName": "附加意外伤害医疗保险",
                     "liabilityAmount": str(int(int(dt["accident_medical"]) / 10000)) + "万"},
                    {"liabilityId": "100019", "amount": dt["disease_hospital"], "liabilityName": "疾病住院医疗保险",
                     "liabilityAmount": str(int(int(dt["disease_hospital"]) / 10000)) + "万"}],
                                  "liabilityContents": [{"liabilityId": "1122031", "amount": dt["accident_death"],
                                                         "liabilityName": "人身意外伤害身故/伤残保险",
                                                         "liabilityAmount": str(
                                                             int(int(dt["accident_death"]) / 10000)) + "万"},
                                                        {"liabilityId": "1122032", "amount": dt["accident_medical"],
                                                         "liabilityName": "附加意外伤害医疗保险", "liabilityAmount": str(
                                                            int(int(dt["accident_medical"]) / 10000)) + "万"},
                                                        {"liabilityId": "100019", "amount": dt["disease_hospital"],
                                                         "liabilityName": "疾病住院医疗保险", "liabilityAmount": str(
                                                            int(int(dt["disease_hospital"]) / 10000)) + "万"}],
                                  "planId": planId},
                "exchangeData": {"memberId": "", "memberToken": "", "applicationId": "1250995219468976128",
                                 "applicationToken": "365a769d8ebf5cbf0e67a3c2b86b029d",
                                 "workqueueId": "1121711509709635584", "channelId": "3", "platformId": "pc",
                                 "referId": ""}, "insuredData": [
                    {"insuredProfessionLevel": level, "insuredProfessionText": text, "insuredProfession": "00201015"}]}

        payload = json.dumps(data)
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and "premium" in r.text:
            prices = [float(price["premium"]) for price in r.json()["data"]["planLiabilityList"]]
            price = Helper.decimalParse(sum(prices))
            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            print(data)
            mysql.updatePrice(data)
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("\n/*产品价格信息更新失败:%d*/" % dt["id"])

    # 获取职业信息
    def getProfessionInfo(self, items=[], data={}):
        jbs = eval(open("./jbs", mode="r", encoding="utf-8").read())
        first_level = []
        second_level = []
        third_level = []
        fourth_level = []

        for x in jbs:
            for y in (x["subList"]):
                for z in y["subList"]:
                    if z["level"] == "1" or z["level"] == 1:
                        first_level.append(z["name"])
                    elif z["level"] == "2" or z["level"] == 2:
                        second_level.append(z["name"])
                    elif z["level"] == "3" or z["level"] == 3:
                        third_level.append(z["name"])
                    elif z["level"] == "4" or z["level"] == 4:
                        fourth_level.append(z["name"])
                    else:
                        pass
        data["1"] = first_level
        data["2"] = second_level
        data["3"] = third_level
        data["4"] = fourth_level
        return (data)
